<template>
  <!-- StartPage 启动页 -->
  <view class="startpage-container" :style="{ backgroundImage: `url(${backgroundImage})` }">
    <Header title="" transparent="always" :is-go-back="false" />
    <view class="loader"></view>
  </view>
</template>

<script lang="ts" setup>
  import { getUrlName, reLaunch, onLoad, switchTab } from '@/router';
  import { useAppStoreWithOut } from '@/store/modules/app';
  import { computed } from 'vue';
  import Header from '@/components/Header/index.vue';
  import { type StartPage } from '@/router/types/modules';
  import { getAppShareLog, readSign } from '@/api';
  import { DynamicTabbarPagesEnum, TabbarPageEnum } from '@/enums/pageEnum';
  import { updateManager } from '@/utils/updateManager';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import { Pages, type PagesType } from '@/router/types/pages';
  import { isObject, isString, isEmpty } from 'lodash-es';
  import { isDynamicPathTabbarPage, isJSON, urlConvertToName } from '@/utils/is';
  import { useEnv } from '@/hooks/core/useEnv';
  import { CacheEnum } from '@/enums/cacheEnum';
  import type { HomeTabResult } from '@/api/dynamicAllocation/types';
  /**  StartPage  启动页 */

  interface ShareLogQueryInter {
    id: number;
    messageId: string;
    userId: number;
  }

  const externalRoute = new Map<string, PagesType>([
    ['e2e47976a7ed41d4904314561d683bd7', 'systemIntroduction'],
  ]);

  const useApp = useAppStoreWithOut();
  const { tabbarApi, isPc, globalConfig } = useApp;
  const backgroundImage = computed(() => globalConfig?.firstScreenFigure);
  const { login } = useUserStoreWithOut();
  const { envVersion } = useEnv();

  const getTabbarList = async () => await tabbarApi();

  const isDynamicTabbar = (path: string) => {
    return DynamicTabbarPagesEnum[
      `BASE_${path.toLocaleUpperCase()}` as keyof typeof DynamicTabbarPagesEnum
    ];
  };

  onLoad<'StartPage'>(async (op) => {
    if (!isPc() && envVersion !== 'develop') {
      await updateManager();
    }

    await getTabbarList();
    const enterOptions = await uni.getEnterOptionsSync();
    const extraData = enterOptions.referrerInfo.extraData as { key: string } | undefined;
    console.log('startPage', enterOptions);
    console.log('startPage', op);

    try {
      await login();
    } catch (error) {}

    if (extraData?.key) {
      op.path = externalRoute.get(extraData.key) as string;
    }

    if (!op || isEmpty(op)) return toTabbar();
    const { path, query } = await getLoadOptions(op);
    const messageId = isObject(query) && (query as ShareLogQueryInter).messageId;
    if (messageId) {
      await readSign(messageId);
    }

    /** 自定义Tabbar页面 */
    if (isDynamicPathTabbarPage(path)) {
      const tabbarList = await getTabbarList();
      const component = query?.component;
      let tabbarItem = tabbarList.find((v) => v.component === component);
      if (tabbarItem) {
        return toTabbar(tabbarItem.pagePath);
      } else if (component) {
        return reLaunchRouter(component, query as Recordable);
      }
    }

    if (path === TabbarPageEnum.BASE_HOME) return toTabbar(TabbarPageEnum.BASE_HOME);
    if (path === TabbarPageEnum.BASE_MINE) return toTabbar(TabbarPageEnum.BASE_MINE);

    reLaunchRouter(path, query as Recordable);
  });

  async function getLoadOptions(op: StartPage): Promise<{ path: string; query: Recordable }> {
    // scene={id} 分享日志方式获取参数
    // 参数格式: { path: string, query: JSON String ==> ShareLogQueryInter  }
    if (op.scene) {
      const res = await getAppShareLog(Number(op.scene));
      return {
        path: res.path,
        query: (isJSON(res.query) || {}) as ShareLogQueryInter,
      };
    }
    // 路径参数形式 op = { path: string, query: JSON String }
    let query: Recordable = isString(op.query) ? isJSON(op.query) || {} : {};
    // query && path 直接返回op对象
    if (query && op.path) return Promise.resolve({ query: query, path: op.path });
    // 有path 无query的情况
    if (op.path) {
      // 若path后有拼接其他参数, 冗余到query中
      const { path, ...lastArg } = op;
      return { path, query: { ...lastArg } };
    }
    // 有query 无path 忽略query 跳转Home
    toTabbar();
    return Promise.reject();
  }

  function reLaunchRouter(path: string, query: Recordable = {}) {
    const routerName = urlConvertToName(path);
    Pages[routerName] ? reLaunch({ name: routerName as any, options: query }) : toTabbar();
  }

  async function toTabbar(tabbarPath?: any) {
    tabbarPath && (tabbarPath = urlConvertToName(tabbarPath));
    switchTab(tabbarPath || TabbarPageEnum.BASE_HOME);
  }
</script>

<style lang="scss" scoped>
  $colors: rgba(337, 84, 48, 0.75) rgba(160, 50, 48, 0.75) rgba(190, 61, 65, 0.75)
    rgba(41, 82, 52, 0.75);
  $size: 2.5em;
  $thickness: 0.5em;

  // Calculated variables.
  $lat: calc(($size - $thickness) / 2);
  $offset: $lat - $thickness;
  .startpage-container {
    width: 100vw;
    height: 100vh;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    .loader {
      width: $size;
      height: $size;
      position: absolute;
      top: calc(50% - $size / 2);
      left: calc(50% - $size / 2);
      transform: rotate(165deg);

      &:before,
      &:after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        display: block;
        width: $thickness;
        height: $thickness;
        border-radius: calc($thickness / 2);
        transform: translate(-50%, -50%);
      }

      &:before {
        animation: before 2s infinite;
      }

      &:after {
        animation: after 2s infinite;
      }
    }

    @keyframes before {
      0% {
        width: $thickness;
        box-shadow: $lat (-$offset) nth($colors, 1), (-$lat) $offset nth($colors, 3);
      }
      35% {
        width: $size;
        box-shadow: 0 (-$offset) nth($colors, 1), 0 $offset nth($colors, 3);
      }
      70% {
        width: $thickness;
        box-shadow: (-$lat) (-$offset) nth($colors, 1), $lat $offset nth($colors, 3);
      }
      100% {
        box-shadow: $lat (-$offset) nth($colors, 1), (-$lat) $offset nth($colors, 3);
      }
    }

    @keyframes after {
      0% {
        height: $thickness;
        box-shadow: $offset $lat nth($colors, 2), (-$offset) (-$lat) nth($colors, 4);
      }
      35% {
        height: $size;
        box-shadow: $offset 0 nth($colors, 2), (-$offset) 0 nth($colors, 4);
      }
      70% {
        height: $thickness;
        box-shadow: $offset (-$lat) nth($colors, 2), (-$offset) $lat nth($colors, 4);
      }
      100% {
        box-shadow: $offset $lat nth($colors, 2), (-$offset) (-$lat) nth($colors, 4);
      }
    }
  }
</style>
